package org.qydjk.console.controller.basic;

import org.qydjk.common.controller.BaseController;
import org.qydjk.common.pojo.Category;
import org.qydjk.common.util.BeanUtil;
import org.qydjk.common.util.StringUtil;
import org.qydjk.common.vo.Tree;
import org.qydjk.console.service.ICategoryService;
import org.qydjk.console.service.impl.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/category")
public class CategoryController extends BaseController {
    @Autowired
    private ICategoryService categoryService;

    @RequestMapping("/category.do")
    public String category() {
        return "basic/category/category";
    }

    @RequestMapping("/treeGrid.do")
    @ResponseBody
    public Object dataGrid(Integer page, Integer rows, String sort, String order) throws Exception {
        try {
            String hql = "FROM Category c ORDER BY c.ord ";
            List<Category> categoryList = baseService.findByHql(hql);
            return categoryList;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    @GetMapping("/addPage.do")
    public String addPage() {
        return "basic/category/categoryAdd";
    }

    /**
     * 查询所有的菜单
     */
    @RequestMapping("/allTree.do")
    @ResponseBody
    public Object allTree() throws Exception {
        try {
            List<Tree> trees = new ArrayList<Tree>();
            // 查询所有菜单
            List<Category> categoryLists = baseService.findByHql("from Category c ORDER BY c.ord");
            if (categoryLists == null) {
                return trees;
            }
            boolean needRoot = true;
            String root = request.getParameter("root");
            if(StringUtil.isEmptyOrNull(root)){
                needRoot = false;
            }
            return buildTree(categoryLists,needRoot);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 构建树
     *
     * @param resourceLists
     * @return
     */
    private List<Tree> buildTree(List<Category> resourceLists,boolean needRoot) {
        try {
            List<Tree> trees = new ArrayList<Tree>();
            for (Category category : resourceLists) {
                Tree tree = new Tree();
                tree.setId(category.getId());
                if((category.getParentId() == null || category.getParentId().intValue() == 0) && needRoot){
                    tree.setPid(-1);
                }else{
                    tree.setPid(category.getParentId());
                }
                tree.setText(category.getName());
                tree.setAttributes(category.getLevel());
                trees.add(tree);
            }
            if(needRoot){
                Tree tree = new Tree();
                tree.setId(-1);
                tree.setPid(null);
                tree.setText("根节点");
                trees.add(tree);
            }
            return trees;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 添加资源
     *
     * @param category
     * @return
     */
    @RequestMapping("/add.do")
    @ResponseBody
    public Object add(@Valid Category category) throws Exception {
        try {
            Date date = new Date();
            category.setCreateTime(date);
            category.setUpdateTime(date);
            updateLevel(category);
            categoryService.saveCategoryAndUpdateParentLeaf(category);
            return renderSuccess("添加成功！");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 修改分类级别
     *
     * @param category
     * @throws Exception
     */
    public void updateLevel(Category category) throws Exception {
        try {
            Integer parentId = category.getParentId();
            if (parentId != null) {
                Category parentCategory = baseService.findSingleByHql("FROM Category c WHERE c.id = " + parentId);
                if (parentCategory != null) {
                    category.setLevel(parentCategory.getLevel() + 1);
                }
            } else {
                category.setLevel(1);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 编辑资源页
     *
     * @param model
     * @param id
     * @return
     */
    @RequestMapping("/editPage.do")
    public String editPage(Model model, Integer id) throws Exception {
        try {
            Category category = baseService.get(Category.class, id);
            model.addAttribute("category", category);
            return "basic/category/categoryEdit";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 编辑资源
     *
     * @param category
     * @return
     */
    @RequestMapping("/edit.do")
    @ResponseBody
    public Object edit(@Valid Category category,Integer oldParentId) throws Exception {
        try {
            Category ss = baseService.get(Category.class, category.getId());
            BeanUtil.copyProperties(category, ss);
            ss.setUpdateTime(new Date());
            updateLevel(ss);
            categoryService.updateCategoryAndUpdateParentLeaf(ss,oldParentId);
            return renderSuccess("编辑成功！");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 删除资源
     *
     * @param id
     * @return
     */
    @RequestMapping("/delete.do")
    @ResponseBody
    public Object delete(Integer id) throws Exception {
        try {
            Category category = new Category();
            category.setId(id);
            List<Category> categoryList = baseService.findByHql("FROM Category c WHERE c.parentId = " + id);
            if (categoryList != null && categoryList.size() > 0) {
                return renderSuccess("当前分类存在子分类,请先删除子分类！");
            } else {
                categoryService.deleteCategoryAndUpdateParentLeaf(category);
                return renderSuccess("删除成功！");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
